﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Reflection;
using System.IO;
using System.Diagnostics;
using System.Data.OleDb;

namespace template_dll
{
    public partial class ChildForm : Form
    {
        public ChildForm()
        {
            InitializeComponent();
        }

        private const string namechcol = "Флаг";
        private SqlConnection conn;
        private DataTable dt_rep;
        private delegate void Deleg();
        private struct date_str { public DateTime dt; public string dtname; }
        private date_str[] dt_str = new date_str[]{ };
        private string urs;
        private NewItem month;
        private object val;
        private DataTable dt_plan;
        private bool Dir;

        public static bool DisplayForm(System.Windows.Forms.Form theMDIParent)
        {
            ChildForm f = new ChildForm();
            f.MdiParent = theMDIParent;
            f.WindowState = FormWindowState.Maximized;
            f.Show();
            return true;
        }

        private string GetServ(string filename)
        {
            string str = "";
            using (StreamReader streamReader = new StreamReader(filename))
            {
                while (!streamReader.EndOfStream)
                {
                    str += streamReader.ReadLine();
                }
            }
            return str;
        }

        private void ChildForm_Load(object sender, EventArgs e)
        {
            try
            {
                conn = new SqlConnection(@"Server=" + GetServ("serv.txt") + ";Database=PharmOLAPDW;Integrated Security=True");
                dt_rep = new DataTable();
                dt_plan = new DataTable();
                SqlCommand getdate = conn.CreateCommand();
                getdate.CommandText = @"pas_MonthSel";
                getdate.CommandTimeout = 300;
                getdate.CommandType = CommandType.StoredProcedure;
                DataTable date = new DataTable();
                if (conn.State == ConnectionState.Closed) conn.Open();
                date.Load(getdate.ExecuteReader());
                if (date.Rows.Count > 0)
                {
                    foreach (DataRow dr in date.Rows)
                    {
                        NewItem ni = new NewItem();
                        ni.ParamID = Convert.ToDateTime(dr[0]);
                        ni.ParamComment = dr[1].ToString();
                        Array.Resize(ref dt_str, dt_str.Length + 1);
                        dt_str[dt_str.Length - 1].dt = Convert.ToDateTime(dr[0]);
                        dt_str[dt_str.Length - 1].dtname = dr[1].ToString();
                        comboBox1.Items.Add(ni);
                        if (DateTime.Now.Date.Month == Convert.ToDateTime(dr[0]).Month)
                            comboBox1.SelectedIndex = comboBox1.Items.Count - 1;
                    }

                }
                date = null;
                getdate = null;

                SqlConnection dep_con = new SqlConnection(@"Server=" + GetServ("serv.txt") + ";Database=SecurityFA;Integrated Security=True");
                SqlCommand dep = dep_con.CreateCommand();
                dep.CommandText = @"pas_DependentSel";
                dep.CommandTimeout = 300;
                dep.CommandType = CommandType.StoredProcedure;
                if (dep_con.State == ConnectionState.Closed) dep_con.Open();
                DataTable dt_dep = new DataTable();
                dt_dep.Load(dep.ExecuteReader());


                if (dt_dep.Rows.Count > 0)
                {
                    Dir = Convert.ToBoolean(dt_dep.Rows[0].ItemArray.GetValue(4));
                    foreach (DataRow dr in dt_dep.Rows) comboBox2.Items.Add(dr[3].ToString());
                }
                if (!Dir)
                {
                    button3.Visible = false;
                    groupBox6.Visible = false;
                    checkBox1.Visible = false;
                    groupBox7.Visible = false;
                    dataGridView2.Visible = false;
                }

                comboBox2.SelectedIndex = 0;
                dep_con.Close();
                dep = null;
                dt_dep = null;
                dep_con = null;
                toolStripStatusLabel1.Text = "";
                //if (dt_str[comboBox1.SelectedIndex].dt < DateTime.Today) checkBox1.Checked = true;

                dateTimePicker1.Value = DateTime.Now.AddDays(-1);
                dateTimePicker2.Value = DateTime.Now.AddDays(-1);
                dateTimePicker3.Value = DateTime.Now.AddDays(-1);
                dateTimePicker4.Value = DateTime.Now.AddDays(-1);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void StartCreateRep(object sender, EventArgs e)
        {
            dataGridView1.DataSource = null;
            dt_rep.Clear();
            urs = comboBox2.Text;
            month = (comboBox1.SelectedItem as NewItem);
            CreateRep();
            dataGridView1.DataSource = dt_rep.DefaultView;

            if (Convert.ToDateTime((comboBox1.SelectedItem as NewItem).ParamID) < DateTime.Today)
            {
                checkBox1.Checked = true;
                checkBox1_CheckedChanged(sender, e);
            }
            GetConst();
            //del = new Deleg(CreateRep);
            //this.Text += " Формируется";
            //IAsyncResult asyncRes = del.BeginInvoke(new AsyncCallback(CallBackFunc), null); //
            //panel1.Enabled = false;
            //dataGridView1.Enabled = false;
        }

        private void GetConst()
        {
            try
            {
                if (conn.State == ConnectionState.Closed) conn.Open();

                SqlCommand myCommand = conn.CreateCommand();
                myCommand.CommandType = CommandType.StoredProcedure;
                myCommand.CommandText = @"pas_URS_Plan_Const";
                myCommand.CommandTimeout = 600;
                myCommand.Parameters.Add("@date", SqlDbType.Date);
                //for (int i = 0; i < dt_str.Length; i++)
                //    if (dt_str[i].dtname == month) 
                myCommand.Parameters["@date"].Value = month.ParamID; //dt_str[i].dt;
                DataTable dt = new DataTable();
                dt.Load(myCommand.ExecuteReader());

                label8.Text = "Всего дней " + dt.Rows[0].ItemArray.GetValue(0).ToString() + ";";
                label9.Text = "Выходных " + dt.Rows[0].ItemArray.GetValue(1).ToString() + ";";
                label10.Text = "Будних " + dt.Rows[0].ItemArray.GetValue(2).ToString() + ";";
                label11.Text = "Коэфф. марк. " + dt.Rows[0].ItemArray.GetValue(3).ToString() + ";";
                label12.Text = "Коэфф.сез.буд. " + dt.Rows[0].ItemArray.GetValue(4).ToString() + "\n вых." + dt.Rows[0].ItemArray.GetValue(5).ToString();
                label12.AutoSize = true;
            }
            catch (Exception ex)
            {
                //this.Invoke((Func<DialogResult>)(() => MessageBox.Show(ex.ToString())));
                MessageBox.Show(ex.ToString());
                conn.Close();
            }

        }

        private void CreateRep()
        {
            try
            {
                if (conn.State == ConnectionState.Closed) conn.Open();

                SqlCommand myCommand = conn.CreateCommand();
                myCommand.CommandType = CommandType.StoredProcedure;
                myCommand.CommandText = @"pas_URS_Plan_newDC";
                myCommand.CommandTimeout = 1800;

                SqlCommand plan = conn.CreateCommand();
                plan.CommandType = CommandType.StoredProcedure;
                plan.CommandText = @"pas_PlanStratSel";
                plan.CommandTimeout = 1800;
                plan.Parameters.Add("@month", SqlDbType.Date);

                myCommand.Parameters.Add("@date", SqlDbType.Date);
                myCommand.Parameters.Add("@date_fer_b", SqlDbType.Date);
                myCommand.Parameters.Add("@date_fer_e", SqlDbType.Date);
                myCommand.Parameters.Add("@date_off_b", SqlDbType.Date);
                myCommand.Parameters.Add("@date_off_e", SqlDbType.Date);
                myCommand.Parameters.Add("@urs", SqlDbType.VarChar, 50);
                myCommand.Parameters.Add("@countpharm", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;

                if (conn.State == ConnectionState.Closed) conn.Open();


                        myCommand.Parameters["@date"].Value = Convert.ToDateTime(month.ParamID);
                        plan.Parameters["@month"].Value = Convert.ToDateTime(month.ParamID);

                myCommand.Parameters["@date_fer_b"].Value = dateTimePicker1.Value;
                myCommand.Parameters["@date_fer_e"].Value = dateTimePicker2.Value;
                myCommand.Parameters["@date_off_b"].Value = dateTimePicker3.Value;
                myCommand.Parameters["@date_off_e"].Value = dateTimePicker4.Value;
                myCommand.Parameters["@urs"].Value = urs;
                
                dt_rep = null;
                dt_rep = new DataTable();             
                dt_rep.Load(myCommand.ExecuteReader());

                if (urs == " Все")
                {
                    dt_plan = null;
                    dt_plan = new DataTable();
                    dataGridView2.DataSource = null;
                    dt_plan.Load(plan.ExecuteReader());
                    foreach (DataRow dr in dt_plan.Rows)
                    {
                            //if (dr[3].ToString() == "общ") label5.Invoke((Func<string>)(() => label5.Text = "Всего: " + Convert.ToInt32(dr[1]).ToString("n0")));
                            //if (dr[3].ToString() == "кор") label6.Invoke((Func<string>)(() => label6.Text = "Кор. бизнес: " + Convert.ToInt32(dr[1]).ToString("n0")));
                            //if (dr[3].ToString() == "разв") label7.Invoke((Func<string>)(() => label7.Text = "Развитие: " + Convert.ToInt32(dr[1]).ToString("n0")));
                            if (dr[0].ToString() == "Вся сеть") label5.Text = "Всего: " + Convert.ToInt32(dr[1]).ToString("n0");
                            if (dr[0].ToString() == "Кор. бизнес") label6.Text = "Кор. бизнес: " + Convert.ToInt32(dr[1]).ToString("n0");
                            if (dr[0].ToString() == "Развитие") label7.Text = "Развитие: " + Convert.ToInt32(dr[1]).ToString("n0");
                    }
                    foreach (DataColumn dc in dt_plan.Columns) dc.ReadOnly = true;
                    dataGridView2.DataSource = dt_plan.DefaultView;
                    dataGridView2.Columns[3].DefaultCellStyle.Format = "p";
                    dataGridView2.Columns[1].DefaultCellStyle.Format = String.Format("n0");
                    dataGridView2.Columns[2].DefaultCellStyle.Format = String.Format("n0");
                    dataGridView2.RowHeadersVisible = false;
                }
                else
                {
                    if (dt_rep.Rows[0].ItemArray[15] != DBNull.Value)
                        //label5.Invoke((Func<string>)(() => label5.Text = "Всего: " + Convert.ToInt32(dt_rep.Rows[0].ItemArray[15]).ToString("n0")));
                        label5.Text = "Всего: " + Convert.ToInt32(dt_rep.Rows[0].ItemArray[15]).ToString("n0");
                    else
                        //label5.Invoke((Func<string>)(() => label5.Text = ""));
                        label5.Text = "";
                    //label6.Invoke((Func<string>)(() => label6.Text = ""));
                    //label7.Invoke((Func<string>)(() => label7.Text = ""));
                    label6.Text = "";
                    label7.Text = "";
                }

                foreach (DataColumn dc in dt_rep.Columns) dc.ReadOnly = true;
                if (Convert.ToDateTime(month.ParamID) < DateTime.Today) checkBox1.Checked = true;
                else checkBox1.Checked = false;
                dt_rep.Columns[12].ReadOnly = false;
                if (Dir)
                {
                    if (checkBox1.Checked) dt_rep.Columns[15].ReadOnly = true;
                    else dt_rep.Columns[15].ReadOnly = false;
                }
                dt_rep.Columns[19].ReadOnly = false;
                dt_rep.Columns[12].ReadOnly = false;
                dt_rep.Columns[13].ReadOnly = false;
                dt_rep.Columns[23].ReadOnly = false;
                dt_rep.Columns[21].ReadOnly = false;
                dt_rep.Columns[24].ReadOnly = false;
                dt_rep.Columns[25].ReadOnly = false;
                dt_rep.Columns[27].ReadOnly = false;
                dt_rep.Columns[28].ReadOnly = false;
                dt_rep.Columns[29].ReadOnly = false;

                //statusStrip1.Invoke((Func<string>)(() => statusStrip1.Items[0].Text = "Всего аптек: " + Convert.ToInt32(myCommand.Parameters["@countpharm"].Value).ToString("n0")));
                statusStrip1.Items[0].Text = "Всего аптек: " + Convert.ToInt32(myCommand.Parameters["@countpharm"].Value).ToString("n0");
                conn.Close();
                myCommand = null;
            }
            catch (Exception ex)
            {
                //this.Invoke((Func<DialogResult>)(() => MessageBox.Show(ex.ToString())));
                MessageBox.Show(ex.ToString());
                conn.Close();
            }

        }

        private void ExpToExcel(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.FileName = "Планирование";
            sfd.Filter = "Excel | *.xls";
            if (sfd.ShowDialog() == DialogResult.OK)
            {   
                SaveDGVToCSVfile(sfd.FileName.ToString(), dataGridView1, true);
            }
        }

        public static bool SaveDGVToCSVfile(string filename, DataGridView table, bool openInExcel)
        {
            try
            {
                StreamWriter sw = new StreamWriter(filename, false, Encoding.Unicode);

                List<int> col_n = new List<int>();
                foreach (DataGridViewColumn col in table.Columns)
                    if (col.Visible)
                    {
                        sw.Write(col.HeaderText + "\t");
                        col_n.Add(col.Index);
                    }
                sw.WriteLine();
                int x = table.RowCount;
                if (table.AllowUserToAddRows) x--;

                for (int i = 0; i < x; i++)
                {
                    for (int y = 0; y < col_n.Count; y++)
                        sw.Write(table[col_n[y], i].Value + "\t");
                    sw.Write(" \r\n");
                }
                sw.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return false;
            }

            if (openInExcel)
            {
                try
                {
                    Process newProc = Process.Start("excel.exe", "\"" + filename + "\"");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
            }
            return true;
        }

        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.Columns[dataGridView1.CurrentCell.ColumnIndex].HeaderText == "Доля чеков план")
            {
                //- Ввод доли чеков


            }
            //MessageBox.Show(dataGridView1[dataGridView1.CurrentCell.RowIndex, dataGridView1.CurrentCell.ColumnIndex].Value.ToString());
            try
            {
                SqlCommand upd = conn.CreateCommand();
                upd.CommandType = CommandType.StoredProcedure;
                upd.CommandText = @"pas_URS_PlanIns";

                int row = dataGridView1.CurrentCell.RowIndex;
                int col = dataGridView1.CurrentCell.ColumnIndex;
                
                upd.Parameters.AddWithValue("@pharmcode", dataGridView1["Код", dataGridView1.CurrentCell.RowIndex].Value);
                upd.Parameters.AddWithValue("@opp_urs", dataGridView1["План продаж", dataGridView1.CurrentCell.RowIndex].Value);
                upd.Parameters.AddWithValue("@strat", dataGridView1["План продаж - стратегия", dataGridView1.CurrentCell.RowIndex].Value);
                upd.Parameters.AddWithValue("@ssp", dataGridView1["ССП план", dataGridView1.CurrentCell.RowIndex].Value);
                upd.Parameters.AddWithValue("@conv", dataGridView1["Конвертация план", dataGridView1.CurrentCell.RowIndex].Value);
                upd.Parameters.AddWithValue("@mplan", dataGridView1["Фармацевты план", dataGridView1.CurrentCell.RowIndex].Value);
                upd.Parameters.AddWithValue("@mfact", dataGridView1["Фармацевты факт", dataGridView1.CurrentCell.RowIndex].Value);
                upd.Parameters.AddWithValue("@opp", dataGridView1["План продаж утвержденный", dataGridView1.CurrentCell.RowIndex].Value);
                upd.Parameters.AddWithValue("@count_chk", dataGridView1["Кратность чека план", dataGridView1.CurrentCell.RowIndex].Value);
                upd.Parameters.AddWithValue("@count_dc", dataGridView1["Доля чеков план", dataGridView1.CurrentCell.RowIndex].Value);
                upd.Parameters.AddWithValue("@month", Convert.ToDateTime(month.ParamID));
                upd.Parameters.Add("@RetVal", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;

                if (conn.State == ConnectionState.Closed) conn.Open();
                upd.ExecuteScalar();
                int ret = (int)upd.Parameters["@RetVal"].Value;
                if (ret == 2 || ret == 0)
                {
                    MessageBox.Show("Изменения не сохранены");
                    dataGridView1.CurrentCell = dataGridView1[col, row];
                    dataGridView1.CurrentCell.Value = val;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            MessageBox.Show("Неверный формат значения");
        }

        private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            val = dataGridView1.CurrentCell.Value;
        }

        private void dataGridView1_DataSourceChanged(object sender, EventArgs e)
        {
            if (dataGridView1.DataSource != null)
            {
                dataGridView1.Columns[0].Frozen = true;
                dataGridView1.Columns[0].Width = 30;
                dataGridView1.Columns[1].Frozen = true;
                dataGridView1.Columns[2].Frozen = true;
                dataGridView1.Columns[2].Width = 70;
                dataGridView1.Columns[3].Frozen = true;
                dataGridView1.Columns[4].Frozen = true;
                dataGridView1.Columns[5].Frozen = true;
                dataGridView1.Columns[5].Width = 60;
                dataGridView1.Columns[dataGridView1.ColumnCount - 1].Visible = false;
                dataGridView1.Columns[dataGridView1.ColumnCount - 2].Visible = false;
                dataGridView1.EnableHeadersVisualStyles = false;
                dataGridView1.Columns[6].HeaderCell.Style.BackColor = Color.Gold;
                dataGridView1.Columns[6].DefaultCellStyle.BackColor = Color.Gold;

                dataGridView1.Columns[19].HeaderCell.Style.BackColor = Color.Orange;
                dataGridView1.Columns[19].DefaultCellStyle.BackColor = Color.Orange;
                
                dataGridView1.Columns[12].HeaderCell.Style.BackColor = Color.SkyBlue;
                dataGridView1.Columns[12].DefaultCellStyle.BackColor = Color.SkyBlue;

                dataGridView1.Columns[10].HeaderCell.Style.BackColor = Color.Aquamarine;
                dataGridView1.Columns[10].DefaultCellStyle.BackColor = Color.Aquamarine;

                dataGridView1.Columns[11].HeaderCell.Style.BackColor = Color.PaleTurquoise;
                dataGridView1.Columns[11].DefaultCellStyle.BackColor = Color.PaleTurquoise;

                dataGridView1.Columns[15].HeaderCell.Style.BackColor = Color.PaleGreen;
                dataGridView1.Columns[15].DefaultCellStyle.BackColor = Color.PaleGreen;

                dataGridView1.Columns[21].HeaderCell.Style.BackColor = Color.SkyBlue;
                dataGridView1.Columns[21].DefaultCellStyle.BackColor = Color.SkyBlue;

                dataGridView1.Columns[23].HeaderCell.Style.BackColor = Color.SkyBlue;
                dataGridView1.Columns[23].DefaultCellStyle.BackColor = Color.SkyBlue;

                dataGridView1.Columns[24].HeaderCell.Style.BackColor = Color.SkyBlue;
                dataGridView1.Columns[24].DefaultCellStyle.BackColor = Color.SkyBlue;

                dataGridView1.Columns[25].HeaderCell.Style.BackColor = Color.SkyBlue;
                dataGridView1.Columns[25].DefaultCellStyle.BackColor = Color.SkyBlue;

                dataGridView1.Columns[28].HeaderCell.Style.BackColor = Color.SkyBlue;
                dataGridView1.Columns[28].DefaultCellStyle.BackColor = Color.SkyBlue;

                dataGridView1.Columns[29].HeaderCell.Style.BackColor = Color.SkyBlue;
                dataGridView1.Columns[29].DefaultCellStyle.BackColor = Color.SkyBlue;

                dataGridView1.Columns[13].DefaultCellStyle.Format = "p";
                dataGridView1.Columns[14].DefaultCellStyle.Format = "p";
                dataGridView1.Columns[22].DefaultCellStyle.Format = "p";
                dataGridView1.Columns[23].DefaultCellStyle.Format = "p";
                dataGridView1.Columns[16].DefaultCellStyle.Format = "p";
                dataGridView1.Columns[17].DefaultCellStyle.Format = "p";
                dataGridView1.Columns[18].DefaultCellStyle.Format = "p";
                dataGridView1.Columns[27].DefaultCellStyle.Format = "p";
                dataGridView1.Columns[29].DefaultCellStyle.Format = "p";
                dataGridView1.Columns[26].DefaultCellStyle.Format = "0.00";
                dataGridView1.Columns[28].DefaultCellStyle.Format = "0.00";
                
                int ii = 6;
                while (ii < 30)
                {
                    if (ii != 13 && ii != 14 && ii != 22 && ii != 23 && ii != 16 && ii != 17 && ii != 18 && ii != 27 && ii != 29 && ii != 26 && ii != 28)
                        dataGridView1.Columns[ii].DefaultCellStyle.Format = String.Format("n0");
                    ii++;
                }
            }
        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            try
            {
                for (int i = 0; i < dataGridView1.RowCount; i++)
                {
                    if (dataGridView1[0, i].Value == DBNull.Value)
                    {
                        if (dataGridView1[4, i].Value == DBNull.Value) dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.LightCoral;
                        else dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.MediumSlateBlue;
                    }
                    else
                        if (Convert.ToBoolean(dataGridView1[dataGridView1.ColumnCount - 2, i].Value) == false)
                        {
                            dataGridView1[2, i].Style.BackColor = Color.Yellow;
                            dataGridView1[1, i].Style.BackColor = Color.Yellow;
                        }
                    if (dataGridView1[dataGridView1.ColumnCount - 1, i].Value != DBNull.Value)
                        if (Convert.ToBoolean(dataGridView1[dataGridView1.ColumnCount - 1, i].Value))
                            dataGridView1[12, i].ReadOnly = true;

                    if (dataGridView1[12, i].Value != DBNull.Value && dataGridView1[15, i].Value != DBNull.Value)
                        if (Convert.ToInt32(dataGridView1[12, i].Value) != Convert.ToInt32(dataGridView1[15, i].Value))
                            dataGridView1[12, i].Style.BackColor = Color.Red;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridView1.DataSource != null)
                {
                    if (!checkBox1.Checked)
                    {
                        SqlCommand upd = conn.CreateCommand();
                        upd.CommandType = CommandType.StoredProcedure;
                        upd.CommandText = @"pas_URS_PlanIns";
                        upd.Parameters.AddWithValue("@month", Convert.ToDateTime((comboBox1.SelectedItem as NewItem).ParamID));

                        upd.Parameters.Add("@pharmcode", SqlDbType.Int);
                        upd.Parameters.Add("@opp", SqlDbType.Int);
                        for (int i = 0; i < dataGridView1.RowCount; i++)
                        {
                            if (dataGridView1["Код", i].Value != DBNull.Value)
                            {
                                upd.Parameters["@pharmcode"].Value = dataGridView1["Код", i].Value;
                                upd.Parameters["@opp"].Value = dataGridView1["План продаж", i].Value;
                                if (conn.State == ConnectionState.Closed) conn.Open();
                                upd.ExecuteScalar();
                                dataGridView1["План продаж утвержденный", i].Value = dataGridView1["План продаж", i].Value;
                            }
                        }
                        StartCreateRep(sender, e);
                        MessageBox.Show("Планы утверждены");
                    }
                    else
                    {
                        MessageBox.Show("Нельзя менять данные в этом месяце. \nEсли все же необходимо это сделать, то снимите блокировку");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (dt_str[comboBox1.SelectedIndex].dt < DateTime.Today) checkBox1.Checked = true;
            //else checkBox1.Checked = false;
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (Dir)
            {
                if (checkBox1.Checked)
                {
                    if (dataGridView1.DataSource != null)
                    {
                        for (int i = 0; i < dataGridView1.ColumnCount; i++)
                            if (i != 24 && i != 25 && i != 19)
                            {
                                dataGridView1.Columns[i].ReadOnly = true;
                            }
                    }
                }
                else
                {
                    if (dataGridView1.DataSource != null)
                    {
                        dataGridView1.DataSource = null;
                        dataGridView1.DataSource = dt_rep.DefaultView;
                        dt_rep.Columns[15].ReadOnly = false;
                        dataGridView1.Columns[15].ReadOnly = false;

                    }
                }
            }
            else
            {
                if (checkBox1.Checked)
                {
                    if (dataGridView1.DataSource != null)
                    {
                        for (int i = 0; i < dataGridView1.ColumnCount; i++)
                            if (i != 24 && i != 25 && i != 19)
                            {
                                dataGridView1.Columns[i].ReadOnly = true;
                                dt_rep.Columns[i].ReadOnly = true;
                            }
                    }

                }
            }
        }
    }
}
